//
//  OAuthViewController.m
//  Weibo-OC
//
//  Created by 焦林生 on 15/11/20.
//  Copyright © 2015年 cn.baidu. All rights reserved.
//

#import "OAuthViewController.h"
#import "NetworkTools.h"

@interface OAuthViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation OAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //加载授权页面
    NSURL *url = [NetworkTools sharedTools].OAuthURL;
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

#pragma mark 设置界面
- (void)loadView {
    self.webView = [[UIWebView alloc]init];
    self.view = self.webView;
    
    self.webView.delegate = self;
    
    self.title = @"登录新浪微博";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
}
- (void)close {

    [self dismissViewControllerAnimated:true completion:nil];
}

//自动填充
- (void)autoFill {

    NSString *js = [NSString stringWithFormat:@"document.getElementById('userId').value = '15893305305@sina.cn';document.getElementById('passwd').value = 'jls123';"];
    //webview执行jsxz
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

#pragma mark UIWebView代理方法
/**
 *  是否加载请求
 *
 *  @param webView        webView
 *  @param request        要加载的请求
 *  @param navigationType 导航类型 页面跳转方式
 *
 *  @return 是否加载当前请求
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // 如果是百度 就不加载
    //1 判断访问的主机是否是百度
    NSURL *url = request.URL;
    if (![url.host  isEqual: @"www.baidu.com"]) {
        return true;
    }
    
    //2 从百度地址的URL中提取'code'是否存在
    NSString *query = url.query;
    ;
    if (![query hasPrefix:@"code="]) {
        return false;
    }
    NSLog(@"%@",query);
    //3 从查询字符串中取出授权码
    NSString *code = [query substringFromIndex:5];
    NSLog(@"%@",code);
    
    //4加载accessToken
    [[NetworkTools sharedTools] loadAccessToken:code finished:^(id result, NSError *error) {
        if (error != nil) {
            NSLog(@"出错了");
            return ;
        }
        
    }];
    return  false;
}

@end
